import React, { useState, useEffect, useRef } from 'react'
import { useSelector } from 'react-redux'
import { Rootstate } from '@/store'
import './home.scss'
import ContentMain from '@/component/conntent/content'
import { getBooksApi } from '@/api/books'
import type { PageInterface } from '#/api'
import type { BooksTitleInterface } from '#/books'
import Layout from '@/component/layout/layout'
import { TagOutlined } from '@ant-design/icons'
import type { MenuProps } from 'antd'
import { useNavigate, useLocation } from 'react-router-dom'

type MenuItem = Required<MenuProps>['items'][number]

/**
 * 获取所有标签
 * @param params
 * @returns
 */
const getBooks = async (params?: PageInterface) => {
  const { code, data } = await getBooksApi(params)
  if (code !== 200) {
    return []
  }
  return data
}

function Home() {
  const { theme: _theme } = useSelector((state: Rootstate) => ({
    theme: state.settings.theme
  }))

  const [books, setBooks] = useState<any[]>([])
  const [items, setItems] = useState<MenuItem[]>([])
  const layoutElement = document.getElementById('layout-content')
  const Navigate = useNavigate()
  const Location = useLocation()

  useEffect(() => {
    const key = Location.hash.split('#')[1] || ''
    const el = document.getElementById(key)
    if (el && layoutElement) {
      layoutElement.scrollTo({ top: el.offsetTop - 10, behavior: 'smooth' })
    }
    // console.log('key', key, el, layoutElement)
  }, [Location.hash, layoutElement, items])

  // 侧边栏点击滚到到指定区域
  const goElement = (key: string) => {
    Navigate(`#${key}`, { replace: true })
  }

  useEffect(() => {
    getBooks().then((data) => {
      setBooks(data.data)
      const title_list = data.data.map((v: any) => ({
        key: v?.id,
        icon: React.createElement(TagOutlined),
        label: v?.name
      }))
      setItems(title_list)
    })
  }, [])

  return (
    <Layout items={items} click={goElement}>
      <ContentMain books={books} />
    </Layout>
  )
}

export default Home
